package com.ebeijia.context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;


/**
 * Created by Yangpengju on 2015/8/17.
 */
public class RequestResponseContext {

    private static ThreadLocal<RequestResponseContext> contextThreadLocal = new ThreadLocal<RequestResponseContext>();

    private HttpServletRequest request;

    private HttpServletResponse response;


    public static void init(HttpServletRequest request, HttpServletResponse response) {
        RequestResponseContext requestResponseContext = new RequestResponseContext();
        contextThreadLocal.set(requestResponseContext);
        requestResponseContext.request = request;
        requestResponseContext.response = response;
    }

    public static HttpServletRequest getRequest() {
        return contextThreadLocal.get().request;
    }

    public static HttpServletResponse getResponse() {
        return contextThreadLocal.get().response;
    }

    public static String getParam(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 得到user context，没有则创建一个
     * @return
     */
    public static UserContext getUserContext() {
        Object sessionObj = getRequest().getSession().getAttribute("userManage");
        if (sessionObj != null) {
            return (UserContext)sessionObj;
        }
        UserContext userContext = new UserContext();
        putUserContext(userContext);
        return userContext;
    }

    private static void putUserContext(UserContext userContext) {
        getRequest().getSession().setAttribute("userManage", userContext);
    }

    public static String getRequestIp() {
        HttpServletRequest request = getRequest();
        String realIP = request.getHeader("x-forwarded-for");
        if (realIP != null && realIP.length() != 0) {
            while ((realIP != null && realIP.equals("unknow"))) {
                realIP = request.getHeader("x-forwarded-for");
            }
        }
        if (realIP == null || realIP.length() == 0) {
            realIP = request.getHeader("Proxy-Clint-IP");
        }
        if (realIP == null || realIP.length() == 0) {
            realIP = request.getHeader("WL-Proxy-Clint-IP");
        }
        if (realIP == null || realIP.length() == 0) {
            realIP = request.getRemoteAddr();
        }
        if (realIP != null && realIP.contains(",")) {
            realIP = realIP.split(",")[0];
        }
        return realIP;
    }

    public static void clear() {
        contextThreadLocal.remove();
        MDC.clear();
    }

    private static RequestResponseContext getContext() {
        return contextThreadLocal.get();
    }


}
